'''
泰康康护一生重大疾病保险产品计划
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from threading import Thread


class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰康康护一生重大疾病保险产品计划"

    # 生成产品数据
    def genProductInfo(self):

        # 实例化数据库
        mysql = MysqlClient()

        # 投保对象 18 - 60
        myself = [str(i) for i in range(18, 61)]
        # 为配偶 18- 60
        spouse = [str(i) for i in range(18, 61)]
        # 为子女 1 - 18
        child = [str(i) for i in range(1, 18)]
        # 性别 1 男 2 女
        gender = ["1", "2"]
        # 保障期间
        interval = ["A70", "A80", "A90", "A105"]
        # 交费方式 SP 一次性缴纳 Y5 5年缴纳
        payment = ["SP", "Y5", "Y10", "Y15", "Y20"]
        # 保险金额 10w 20w 50w 100w 200w
        money = ["10", "20", "50", "100", "200"]

        for x in [myself, spouse, child]:

            for v in product(x, gender, interval, payment, money):

                # 保底缴纳15年
                if int(v[0]) > 55 and v[2] == "A70":
                    continue

                # 写入数据库
                mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))
                mysql._conn.commit()

                print("写入产品信息成功~~")

    # 执行爬虫
    def requestJson(self,dt,mysql):

        # 获取当前年份
        forYear = 2019

        data = {

            "calculateData": {
                "calapplicantArea": "3,30",
                "calapplicantAreaTxt": "广东 东莞",
                "insuredInfo": [{
                    "calinsuredRelationship": "30",
                    "calinsuredGender": dt["gender"],
                    "calinsuredBirth": "{year}-10-01".format( year = str(forYear - int(dt["year"])))
                }],
                "calpayPeriod": dt["payment"],
                "calinsuredPeriod": dt["interval"],
                "planId": "1037",
                "calpayType": "Y",
                "planLiabilityList": [{
                    "liabilityId": "5981",
                    "amount": "{num}0000".format( num = dt["money"]),
                    "liabilityName": "泰康康护一生两全保险期缴",
                    "liabilityAmount": "",
                    "premium": ""
                }, {
                    "liabilityId": "5983",
                    "amount": "{num}0000".format( num = dt["money"]),
                    "liabilityName": "泰康附加康护一生重大疾病保险期缴",
                    "liabilityAmount": "",
                    "premium": ""
                }],
                "calstartDate": "2020-01-02 00:00:00"
            },
            "exchangeData": {
                "memberId": "",
                "memberToken": "",
                "applicationId": "1205364814069866496",
                "applicationToken": "474168a91d8e6ddccbe99eade4b270da",
                "workqueueId": "950216444110815232",
                "channelId": "3",
                "sign_url": "https://m.tk.cn/product/mobile/v2/signature/policy_signature.html?applicationId=1205364814069866496&applicationToken=474168a91d8e6ddccbe99eade4b270da"
            }
        }


        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=json.dumps( data ))

        try:
            if r.status_code == 200:

                totalPrice = r.json()["data"]["sumPremium"]

                price = Helper.decimalParse( totalPrice )

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                mysql.updatePrice( data )

        except Exception as e:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask( data )

            print("数据结果异常,失败任务标记完成:",dt["id"])


    def main(self,mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt,mysql)

    def startProcess(self):

        # 生成产品数据
        self.genProductInfo()
        print("产品信息任务生成完毕,开始执行任务...")

        for i in range( 5 ):

            mysql = MysqlClient()

            t = Thread( target=self.main,args=(mysql,))

            t.start()

